/**
 * 通用CRUD
 * @param {*} app 
 */


module.exports = app => {
  const router = require('express').Router()
  const seqUtil = require('../../utils/seqUtil')

  // 查询全部
  router.get('/', async (req, res, next) => {
    try {
      const model = await req.Model.findAndCountAll({
        where: seqUtil.sequelizeJsonLike(req.query) || null,
        limit: Number(req.query.pageSize) || null,
        offset: Number(req.query.pageSize) * (Number(req.query.currentPage) - 1) || null
      })
      res.response(200, '查询成功', model)
    } catch (error) {
      next(error)
    }
  })

  // 详情查询
  router.get('/:id', async (req, res, next) => {
    try {
      const model = await req.Model.findOne({ where: { id: req.params.id } })
      res.response(200, '获取成功', model)
    } catch (error) {
      next(error)
    }
  })

  // 提交数据
  router.post('/', async (req, res, next) => {
    try {
      const model = await req.Model.create(req.body)
      res.response(200, '添加成功', model)
    } catch (error) {
      next(error)
    }
  })

  // 修改数据
  router.put('/:id', async (req, res, next) => {
    try {
      const model = await req.Model.update(req.body, { where: { id: req.params.id } })
      res.response(200, '修改成功', model)
    } catch (error) {
      next(error)
    }
  })


  // 删除单条数据
  router.delete('/:id', async (req, res, next) => {
    try {
      const model = await req.Model.destroy({ where: { id: req.params.id } })
      res.response(200, '删除成功', model)
    } catch (error) {
      next(error)
    }
  })


  // 删除多条数据
  router.delete('/', async (req, res, next) => {
    try {
      let ids = req.query.ids.split(',')
      ids.forEach(async id => {
        await req.Model.destroy({ where: { id: id } })
      })
      res.response(200, '删除成功')
    } catch (error) {
      next(error)
    }
  })


  const resource = require('../../middleware/resource')
  const httpAuth = require('../../middleware/httpAuth')

  app.use('/admin/api/rest/:resource', httpAuth(), resource(), router)
}